import pygame
import os

class Zombie:
    def __init__(self, x, y):
        """
        初始化僵尸对象
        :param x: 起始x坐标
        :param y: 起始y坐标
        """
        self.x = x
        self.y = y
        self.images = []
        self.current_frame = 0
        self.animation_speed = 5  # 控制动画播放速度
        self.frame_count = 0
        self.move_speed = 1  # 移动速度

        # 加载僵尸行走动画帧
        self.load_images()

    def load_images(self):
        """加载僵尸行走的所有动画帧"""
        for i in range(1, 23):  # 1.png 到 22.png
            image_path = f"images/普通/{i}.png"
            if os.path.exists(image_path):
                image = pygame.image.load(image_path)
                self.images.append(image)
            else:
                print(f"警告: 找不到图片 {image_path}")

        if not self.images:
            print("错误: 没有成功加载任何僵尸动画帧")

    def update(self):
        """更新僵尸动画帧并移动"""
        # 更新动画帧
        self.frame_count += 1
        if self.frame_count >= self.animation_speed:
            self.current_frame = (self.current_frame + 1) % len(self.images)
            self.frame_count = 0

        # 移动僵尸
        self.x -= self.move_speed

    def draw(self, screen):
        """在屏幕上绘制僵尸"""
        if self.images:
            current_image = self.images[self.current_frame]
            screen.blit(current_image, (self.x, self.y))

    def get_rect(self):
        """获取僵尸的矩形区域，用于碰撞检测"""
        if self.images:
            current_image = self.images[self.current_frame]
            return pygame.Rect(self.x, self.y, current_image.get_width(), current_image.get_height())
        return pygame.Rect(self.x, self.y, 0, 0)

    def collides_with(self, sunflower):
        """检测是否与向日葵发生碰撞"""
        return self.get_rect().colliderect(sunflower.get_rect())

class Sunflower:
    def __init__(self, x, y):
        """
        初始化向日葵对象
        :param x: 起始x坐标
        :param y: 起始y坐标
        """
        self.x = x
        self.y = y
        self.images = []
        self.current_frame = 0
        self.animation_speed = 8  # 控制动画播放速度
        self.frame_count = 0
        self.load_images()

    def load_images(self):
        """加载向日葵的所有动画帧"""
        for i in range(1, 19):  # 1.png 到 18.png
            image_path = f"images/向日葵/{i}.png"
            if os.path.exists(image_path):
                image = pygame.image.load(image_path)
                self.images.append(image)
            else:
                print(f"警告: 找不到图片 {image_path}")

    def update(self):
        """更新向日葵动画帧"""
        self.frame_count += 1
        if self.frame_count >= self.animation_speed:
            self.current_frame = (self.current_frame + 1) % len(self.images)
            self.frame_count = 0

    def draw(self, screen):
        """在屏幕上绘制向日葵"""
        if self.images:
            current_image = self.images[self.current_frame]
            screen.blit(current_image, (self.x, self.y))

    def get_rect(self):
        """获取向日葵的矩形区域，用于碰撞检测"""
        if self.images:
            current_image = self.images[self.current_frame]
            return pygame.Rect(self.x, self.y, current_image.get_width(), current_image.get_height())
        return pygame.Rect(self.x, self.y, 0, 0)

def main():
    """主函数"""
    # 初始化pygame
    pygame.init()

    # 设置屏幕尺寸
    screen_width = 800
    screen_height = 600
    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption("植物大战僵尸 - 多个移动僵尸和向日葵")

    # 设置时钟
    clock = pygame.time.Clock()

    # 加载背景图片
    background_image = None
    background_path = "images/beijing.jpg"
    if os.path.exists(background_path):
        background_image = pygame.image.load(background_path)
        # 调整背景图片大小以适应屏幕
        background_image = pygame.transform.scale(background_image, (screen_width, screen_height))
    else:
        print(f"警告: 找不到背景图片 {background_path}")

    # 加载僵尸胜利图片
    zombies_won_image = None
    zombies_won_path = "ZombiesWon.jpg"
    if os.path.exists(zombies_won_path):
        zombies_won_image = pygame.image.load(zombies_won_path)
        zombies_won_image = pygame.transform.scale(zombies_won_image, (screen_width, screen_height))
    else:
        print(f"警告: 找不到僵尸胜利图片 {zombies_won_path}")

    # 加载锤子图片作为鼠标指针
    hammer_image = None
    hammer_path = "images/hammer.png"
    if os.path.exists(hammer_path):
        hammer_image = pygame.image.load(hammer_path)
        # 设置鼠标指针大小
        hammer_cursor = pygame.cursors.Cursor((hammer_image.get_width()//2, hammer_image.get_height()//2), hammer_image)
        pygame.mouse.set_cursor(hammer_cursor)
    else:
        print(f"警告: 找不到锤子图片 {hammer_path}")

    # 游戏状态
    game_state = "playing"  # "playing" 或 "zombies_won"

    # 定义行位置，使僵尸和向日葵在同一条横线上对齐
    row_positions = [100, 200, 300, 400, 500]

    # 创建多个僵尸实例，每行一个
    zombies = []
    for y in row_positions:
        zombies.append(Zombie(700, y))  # 僵尸从右側开始

    # 创建多个向日葵实例，每行一个
    sunflowers = []
    for y in row_positions:
        sunflowers.append(Sunflower(100, y))  # 向日葵在左側固定位置

    # 游戏主循环
    running = True
    while running:
        # 处理事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            # 如果游戏结束，按任意键退出
            elif event.type == pygame.KEYDOWN and game_state == "zombies_won":
                running = False
            # 处理鼠标点击事件
            elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:  # 左键点击
                mouse_x, mouse_y = event.pos
                # 检查点击位置是否在某个僵尸上
                for zombie in zombies[:]:  # 使用副本避免在迭代时修改列表
                    if zombie.get_rect().collidepoint(mouse_x, mouse_y):
                        # 点击到僵尸，移除僵尸
                        if zombie in zombies:
                            zombies.remove(zombie)
                        break

        if game_state == "playing":
            # 更新所有僵尸动画和位置
            for zombie in zombies[:]:  # 使用副本避免在迭代时修改列表
                zombie.update()

                # 可选：当僵尸移出屏幕时重置位置
                if zombie.x < -100:  # 注意：因为僵尸向左移动，所以判断条件也相应改变
                    zombie.x = screen_width  # 从屏幕右侧重新出现

            # 更新所有向日葵动画
            for sunflower in sunflowers:
                sunflower.update()

            # 检查碰撞
            for zombie in zombies[:]:  # 使用副本避免在迭代时修改列表
                for sunflower in sunflowers[:]:
                    if zombie.collides_with(sunflower):
                        # 发生碰撞，只移除向日葵，不移除僵尸
                        if sunflower in sunflowers:
                            sunflowers.remove(sunflower)

                        # 修改这里：一旦任意向日葵被吃掉，游戏立即结束
                        game_state = "zombies_won"
                        break  # 跳出内层循环
                if game_state == "zombies_won":
                    break  # 跳出外层循环

            # 检查是否所有僵尸都被消灭
            if not zombies:
                game_state = "all_zombies_defeated"

        # 绘制
        if game_state == "zombies_won" and zombies_won_image:
            screen.blit(zombies_won_image, (0, 0))
        elif game_state == "zombies_won":
            screen.fill((0, 0, 0))  # 黑色背景作为备选
            # 使用提供的图片作为胜利画面
            font = pygame.font.Font(None, 74)
            text = font.render("ZombiesWon", True, (255, 0, 0))
            text_rect = text.get_rect(center=(screen_width//2, screen_height//2))
            screen.blit(text, text_rect)
        elif game_state == "all_zombies_defeated":
            screen.fill((0, 0, 0))  # 黑色背景作为备选
            # 显示僵尸全部被消灭的文字
            font = pygame.font.Font(None, 74)
            text = font.render("YOUWIN!", True, (0, 255, 0))
            text_rect = text.get_rect(center=(screen_width//2, screen_height//2))
            screen.blit(text, text_rect)
        else:
            if background_image:
                screen.blit(background_image, (0, 0))  # 绘制背景图片
            else:
                screen.fill((135, 206, 235))  # 填充天空蓝背景作为备选

            # 绘制所有僵尸
            for zombie in zombies:
                zombie.draw(screen)

            # 绘制所有向日葵
            for sunflower in sunflowers:
                sunflower.draw(screen)

        # 更新显示
        pygame.display.flip()

        # 控制帧率
        clock.tick(60)

    # 退出pygame
    pygame.quit()

if __name__ == "__main__":
    main()



# class Sun:
# import pygame
# import os
#
# class Sun:
#     def __init__(self, x, y):
#         """
#         初始化阳光对象
#         :param x: 起始x坐标
#         :param y: 起始y坐标
#         """
#         self.x = x
#         self.y = y
#         self.images = []
#         self.current_frame = 0
#         self.animation_speed = 5
#         self.frame_count = 0
#         self.load_images()
#
#     def load_images(self):
#         """加载阳光旋转的所有动画帧"""
#         for i in range(1, 23):  # 1.png 到 22.png
#             image_path = f"images/sun/{i}.png"
#             if os.path.exists(image_path):
#                 image = pygame.image.load(image_path)
#                 self.images.append(image)
#             else:
#                 print(f"警告: 找不到图片 {image_path}")
#
#         if not self.images:
#             print("错误: 没有成功加载任何阳光动画帧")
#
#     def update(self):
#         """更新阳光动画帧"""
#         self.frame_count += 1
#         if self.frame_count >= self.animation_speed:
#             self.current_frame = (self.current_frame + 1) % len(self.images)
#             self.frame_count = 0
#
#     def draw(self, screen):
#         """在屏幕上绘制阳光"""
#         if self.images:
#             current_image = self.images[self.current_frame]
#             screen.blit(current_image, (self.x, self.y))
#
# def main():
#     """主函数"""
#     # 初始化pygame
#     pygame.init()
#
#     # 设置屏幕尺寸
#     screen_width = 800
#     screen_height = 600
#     screen = pygame.display.set_mode((screen_width, screen_height))
#     pygame.display.set_caption("植物大战僵尸 - 阳光旋转动画")
#
#     # 设置时钟
#     clock = pygame.time.Clock()
#
#     # 创建阳光实例
#     sun = Sun(300, 200)
#
#     # 游戏主循环
#     running = True
#     while running:
#         # 处理事件
#         for event in pygame.event.get():
#             if event.type == pygame.QUIT:
#                 running = False
#
#         # 更新阳光动画
#         sun.update()
#
#         # 绘制
#         screen.fill((135, 206, 235))  # 填充天空蓝背景
#         sun.draw(screen)
#
#         # 更新显示
#         pygame.display.flip()
#
#         # 控制帧率
#         clock.tick(60)
#
#     # 退出pygame
#     pygame.quit()
#
# if __name__ == "__main__":
#     main()
#使用pygame模块
#实现植物大战僵尸中向日葵动态的代码
#图片路径:images/向日葵/1.png到18.png共18张图片